﻿using System;
using System.Linq;

namespace ALDIOrganizer
{
    public partial class MainForm
    {
        private void SQLiteAccess_OnDataChanged(
            Int64 pAffectedEmployeeID,
            int[] pAffectedTables,
            DateTime? pBeginningOfAffectedPeriod,
            DateTime? pEndOfAffectedPeriod)
        {
            var employeesAffected = pAffectedTables.Contains(0);
            var contractsAffected = pAffectedTables.Contains(1);
            var holidaysAffected  = pAffectedTables.Contains(2);
            var requestsAffected  = pAffectedTables.Contains(3);

            if (holidaysAffected |
                employeesAffected)
            {
                DataBind_sheetEmployeesHolidays();
            }
            if (holidaysAffected)
            {
                lvHolidays_Populate();
                lvHolidaysPending_Populate();                

                var pending = SQLiteAccess.GetPendingHolidaysCount((int)cbYear.SelectedValue);                
                cbShowPending.Enabled = pending > 0;
            }
            if (contractsAffected)
            {
                svRota.RefreshRefillRota();
            }
            var ids = SQLiteAccess.GetEmployeeIDs(pAffectedEmployeeID);
            foreach (var id in ids)
            {
                svRota.RefreshEmployeesRow(id);
            }
            if (holidaysAffected)
            {
                Program.CurrentFile.ComputeHolidays(pAffectedEmployeeID);
            }
            if (contractsAffected |
                holidaysAffected)
            {
                var rotasAffected = Program.CurrentFile.GetAllRotasWithin(
                    pBeginningOfAffectedPeriod,
                    pEndOfAffectedPeriod);
                foreach (var rota in rotasAffected)
                {
                    rota.RecomputeTotalHoursField();
                    if (!holidaysAffected)
                    {
                        continue;
                    }
                    rota.RecomputeWhoOnHolidaysField();                        
                    rota.RecomputeTotalHoursField();
                }
            }
            if (requestsAffected)
            {
                dgridRequests_Populate();
                dgridRequestsPending_Populate();
            }
            SetTitlesOfHolidaysAndRequestsTabs(
                holidaysAffected,
                requestsAffected);   
        }
    }
}
